package jlu.com.p2pclient.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.jlu.mcloud.rpc.client.RPCClient;
import com.jlu.p2pserver.IFileQuery;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import jlu.com.p2pclient.R;
import jlu.com.p2pclient.utils.Config;

/**
 * @Author freedom
 * @DATE 2017/5/25 0025 9:05.
 * see    获取服务器文件类
 */

public class FileNameActivity extends AppCompatActivity {

    private ListView listView;
    private List<String> sList;
    private ArrayAdapter<String> adapter;
    /*更新ui*/
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x11) {
                adapter.notifyDataSetChanged();
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fiename_activity);
        //找到控件
        listView = (ListView) findViewById(R.id.file_name_view);
        //获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    IFileQuery fileQuery = RPCClient.getRemoteProxyObject(IFileQuery.class, new InetSocketAddress(Config.SERVER_IP, Config.SERVER_PORT));
                    List<String> sListtmp = fileQuery.queryFiles();//更新sList内存
                    sList.clear();
                    for (String item : sListtmp) {
                        sList.add(item);
                    }
                    Message message = Message.obtain();
                    message.what = 0x11;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

        //设置适配器
        sList = new ArrayList<>();
        adapter = new ArrayAdapter<String>(FileNameActivity.this, android.R.layout.simple_list_item_single_choice, sList);
        listView.setAdapter(adapter);
        //设置选择模式
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

        //设置点击事件,返回数据
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String fileName = sList.get(position);
                Intent intent = new Intent();
                intent.putExtra("fileName", fileName);
                setResult(RESULT_OK, intent);
                finish();
            }
        });

    }


}
